package org.hzero.business.halm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.choerodon.core.exception.CommonException;
import org.hzero.business.halm.dto.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 处理halm系统中tp_change_line中得attribute字段
 * 类似：{"curr":"1&@&信息类资产","target":"1&@&信息类资产"}
 * 以及这样得数据{"curr":"1719.50","target":"1719.50"}
 * @author: tianhao.luo@hand-china.com 2020/12/8  14:56
 */
public class AtnAttributeUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(AtnAttributeUtil.class);

    /**
     * TpChangeLine attitude字段中的目标字段
     */
    private static final String TARGET = "target";
    /**
     * TpChangeLine attitude字段中的原始字段
     */
    private static final String CURR = "curr";

    private static final String ATTRIBUTE = "attribute";

    /**
     * 获取对象中的attribute字段
     *
     * @param obj 行
     * @return 以attribute为键、数据为值的map
     */
    public static <T> Map<String, Attribute> getAttributeMap(T obj) {
        Assert.notNull(obj,"获取attribute字段的对象不能为空！");
        Map<String, Attribute> map = new HashMap<>(22);
        Class<?> aClass = obj.getClass();
        Field[] fields = aClass.getDeclaredFields();
        //拷贝attribute字段
        for (Field field :
                fields) {
            String name = field.getName();
            // 只匹配attribute字段
            if (name.contains(ATTRIBUTE) && name.matches(ATTRIBUTE+"[0-9]+")) {
                field.setAccessible(true);
                String attribute = null;
                try {
                    attribute = (String) field.get(obj);
                } catch (IllegalAccessException e) {
                    LOGGER.error(e.getMessage());
                    throw new CommonException("获取attributeMap失败");
                }
                //能被解析成Attribute
                if (!StringUtils.isEmpty(attribute)) {
                    if (attribute.contains(CURR)||attribute.contains(TARGET)){
                        JSONObject jsonObject = JSON.parseObject(attribute);
                        String curr = jsonObject.getString(CURR);
                        String target = jsonObject.getString(TARGET);
                        Attribute attributeTemp = new Attribute();
                        attributeTemp.setCurr(curr);
                        attributeTemp.setTarget(target);
                        map.put(field.getName(), attributeTemp);
                    }
                }
            }
        }
        return map;
    }
}
